package com.hmall.item.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmall.api.dto.ItemDTO;
import com.hmall.api.dto.OrderDetailDTO;
import com.hmall.common.exception.BizIllegalException;
import com.hmall.common.utils.BeanUtils;
import com.hmall.item.domain.po.Item;
import com.hmall.item.mapper.ItemMapper;
import com.hmall.item.service.IItemService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.Duration;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * <p>
 * 商品表 服务实现类
 * </p>
 *
 * @author 虎哥
 */
@Service
public class ItemServiceImpl extends ServiceImpl<ItemMapper, Item> implements IItemService {

    @Transactional
    public void deductStock(List<OrderDetailDTO> items) {
        for (OrderDetailDTO item : items) {
            int i = baseMapper.updateStock(item);
            if(i<=0){
                throw new BizIllegalException("库存不足！");
            }
        }
    }

    @Override
    public List<ItemDTO> queryItemByIds(Collection<Long> ids) {
        return BeanUtils.copyList(listByIds(ids), ItemDTO.class);
    }

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Override
    public List<ItemDTO> queryItemByIdsCache(Collection<Long> ids) {
        List<ItemDTO> dtoList = new ArrayList<>();
        //循环处理每个商品id
        for (Long id : ids) {
            //优先查询缓存
            Item item = (Item) redisTemplate.opsForValue().get("hmall:item:" + id);
            //如果找不到缓存
            if (item == null) {
                //从数据库中查询商品
                item = getById(id);
                //如果找到了，就把商品缓存到redis里，有效期1小时
                if (item != null) {
                    redisTemplate.opsForValue().set("hmall:item:"+id, item, Duration.ofHours(1));
                }
            }
            //将商品转换成ItemDTO对象，添加到集合中
            dtoList.add(BeanUtil.copyProperties(item, ItemDTO.class));
        }
        return dtoList;
    }

}
